package com.ai.bitcoin.common.trace;

import com.ai.bitcoin.thread.pool.ProcessContext;
import org.slf4j.MDC;

import java.util.Map;
import java.util.UUID;

/**
 * 系统跟踪工具类
 */
public class TraceUtil {
    public final static String TRACE_ID = "_traceId";

    public static void initTrace() {
        String traceId = generateTraceId();
        setTraceId(traceId);
    }


    public static void initTraceFrom(Map map) {
        String traceId = (String) map.get(TRACE_ID);
        if (traceId == null) {
            traceId = generateTraceId();
        }
        setTraceId(traceId);
    }
    public static void initTraceFrom(ProcessContext context) {
        String traceId = context.getTraceId();
        if (traceId == null) {
            traceId = generateTraceId();
        }
        setTraceId(traceId);
    }

    public static void clearTrace() {
        MDC.remove(TRACE_ID);
    }

    public static String getTraceId() {
        return MDC.get(TRACE_ID);
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_ID, traceId);
    }

    static private String generateTraceId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }
}
